package hong.jun.funure;

import hong.jun.lock.Data;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 说明:
 * Created on 2023/10/26 16:15
 *
 * @author yanghongjun <1737619387@qq.com>
 */
public class Main {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        AtomicInteger count = new AtomicInteger();
        try (ExecutorService executorService = Executors.newVirtualThreadPerTaskExecutor()) {
            for (int i = 0; i < 30; i++) {
                //返回结果
                Future<?> submit = executorService.submit(() -> add(count));
                if (i % 2 == 0) {
                    System.out.println(submit.get());//get方法会阻塞
                }
                System.out.println("执行结果" + submit.get());
                boolean done = submit.isDone();
                System.out.println("执行完成" + done);
            }

        } catch (ExecutionException | InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("结果 count:" + count);
        //根据传入的参数获取结果改变
        Data a = new Data();
        Future<Data> submit = Executors.newVirtualThreadPerTaskExecutor().submit(new ThreadFunureTask(a), a);
        Data data = submit.get();
        System.out.println(data.getCount());
        //FutureTask工具类
        FutureTask<Integer> futureTask = new FutureTask<>(() -> 1 + 2);//创建FutureTask
        Thread t1 = new Thread(futureTask);
        t1.start();
        Integer result = futureTask.get();
        System.out.println("FutureTask获取结果" + result);
    }

    public static AtomicInteger add(AtomicInteger i) {
        i.incrementAndGet();
        return i;
    }

}
